<!DOCTYPE html>
<html>

<head>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
    <title>gb28181 talk</title>
    <script src="./axios.min.js"></script>
</head>

<body>

    <div>
        <audio id="local_video" muted controls autoplay width="300" height="200"></audio>

    </div>

    <button onclick="push()">发布流+喊话</button>

    <button onclick="talk_to_device()">喊话</button>

    <button onclick="bye()">挂断</button>

    <script>

        var stream_server = "http://192.168.1.102:33333"
        var device = "34020000001320000564"
        var channel = "34020000001320000001"

        var stream_path = "test_rtc"

        var local_video = document.getElementById("local_video")
        var count = 0
        var timer = null
        // 本地的peer端
        //创建网络连接
        let rtcpeer = new RTCPeerConnection(null);

        async function push() {
            try {
                let sdp = null
                console.log("2.向远端发送offer")

                let stream = await navigator.mediaDevices.getUserMedia({
                    video: false, audio: true
                })

                local_video.srcObject = stream

                var audio_tracks = stream.getAudioTracks()

                if (audio_tracks.length <= 0) {
                    alert("audio track不足0")
                    return
                }

                rtcpeer.addTransceiver(audio_tracks[0], {
                    direction: "sendonly"
                })



                ///主动向远程终端发起视频会话请求
                await rtcpeer.createOffer().then(des => {
                    ///设置视频源触发icecandidate事件 
                    rtcpeer.setLocalDescription(des);
                    console.log("设置本地描述")
                    sdp = des
                });

                if (sdp == null) {
                    console.log("sdp 为空")
                    return
                }



                let url = stream_server + "/api/v1/stream/rtc/publish"
                let headers = {
                    'Content-Type': 'application/json',
                }
                let recv_sdp_obj = null
                let data = JSON.stringify({
                    "stream_path": stream_path,
                    "sdp": sdp
                })
                axios({
                    method: 'post',
                    url: url,
                    data: data
                }).then(async function (response) {
                    if (response.data) {
                        await rtcpeer.setRemoteDescription(
                            new RTCSessionDescription(response.data.data)
                        );

                        talk_to_device()

                    }

                });
            } catch (e) {
                console.log(e)
                alert(e)
            }
        }

        function talk_to_device() {
            timer = setInterval(async () => {
                count++
                if (count >= 40) {
                    clearInterval(timer)
                    timer = null
                }

                talk().then(r => {
                    console.log("talk 成功")
                    clearInterval(timer)
                    timer = null
                }).catch(e => {
                    console.log("talk 失败" + e)
                })


            }, 500)
        }
        var talk_id = ""
        async function talk() {
            return new Promise((result, reject) => {
                try {
                    let url = stream_server + "/api/v1/gb28181/talk"
                    let headers = {
                        'Content-Type': 'application/json',
                    }
                    let recv_sdp_obj = null
                    let data = JSON.stringify({
                        "subscribe_streampath": stream_path,
                        "device_id": device,
                        "channel": channel
                    })

                    axios({
                        method: 'post',
                        url: url,
                        data: data
                    }).then(async function (response) {
                        let obj = response.data
                        if (obj.state) {
                            talk_id = obj.data
                            result()
                        } else {
                            reject("请求失败" + obj.error)
                        }
                    });
                } catch (e) {
                    console.log(e)
                    reject(e)
                }
            })

        }


        function bye() {
            try {
                let url = stream_server + "/api/v1/gb28181/talk/bye"
                let headers = {
                    'Content-Type': 'application/json',
                }
                let recv_sdp_obj = null
                let data = JSON.stringify({
                    "device_id": device,
                    "channel": channel,
                    "talk_id":talk_id
                })

                axios({
                    method: 'post',
                    url: url,
                    data: data
                }).then(async function (response) {
                    console.log(response.data)
                });
            } catch (e) {
                console.log(e)
            }
        }
    </script>
</body>

</html>